import sys


def ctm2hyp(ctm_path):
    hyp = {}
    with open(ctm_path, 'r') as fin:
        utt = None
        content = []
        for line in fin:
            data = line.split( )
            _utt, _channel, _start, _end, _char, _ = data

            if utt is not None:
                if utt != _utt:
                    hyp[utt] = content
                    content = []
                    utt = _utt
            else:
                utt = _utt

            content.append(_char)
        if utt is not None:
            hyp[utt] = content
    return hyp


def hyp2file(hyp, hyp_path):
    with open(hyp_path, "w") as fout:
        for utt in hyp:
            print("{content}({utt})".format(content=" ".join(hyp[utt]), utt=utt), file=fout)


def main(ctm_path, hyp_out_path):
    hyp = ctm2hyp(ctm_path)
    hyp2file(hyp, hyp_out_path)


if __name__ == "__main__":

    if len(sys.argv) != 3:
        exit(-1)
    ctm_path = sys.argv[1]  # "/data/cfs/asr_work/meichaoyang001/aisearch_gpu_home_new/.tmp/jianwei_athena/test.ctm"
    hyp_out_path = sys.argv[2]  # "/data/cfs/asr_work/meichaoyang001/aisearch_gpu_home_new/.tmp/jianwei_athena/test.hyp"

    main(ctm_path, hyp_out_path)
